﻿using Caliburn.Micro;
using KouDai.WinPad.Helper;
using KouDai.WinPad.Initial;
using KouDai.WinPad.Views;
using System;
using System.Collections.Generic;
using System.Reflection;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml.Controls;

// The Grid App template is documented at http://go.microsoft.com/fwlink/?LinkId=234226

namespace KouDai.WinPad
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    public sealed partial class App 
    {
        private WinRTContainer container;
        /// <summary>
        /// Initializes the singleton Application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            InitializeComponent();
        }

        protected override void Configure()
        {
            container = new WinRTContainer();
            container.RegisterWinRTServices();
            new WinRTInitializer().Init();
        }

        private static bool IsConcrete(Type service)
        {
            var serviceInfo = service.GetTypeInfo();
            return !serviceInfo.IsAbstract && !serviceInfo.IsInterface;
        }

        protected override object GetInstance(Type service, string key)
        {
            var obj = container.GetInstance(service, key);

            // mimic previous behaviour of WinRT SimpleContainer
            if (obj == null && IsConcrete(service))
            {
                container.RegisterPerRequest(service, key, service);
                obj = container.GetInstance(service, key);
            }

            return obj;
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }

        protected override void PrepareViewFirst(Frame rootFrame)
        {
            BusyInicator.Instance.Init(rootFrame);
            container.RegisterNavigationService(rootFrame);
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            DisplayRootView<ShellPage>();
        }

        protected override void OnSearchActivated(SearchActivatedEventArgs args)
        {
            DisplayRootView<SearchPage>(args.QueryText);
        }

        //protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
        //{
        //    // Normally wouldn't need to do this but need the container to be initialised
        //    Initialise();

        //    container.Instance(args.ShareOperation);

        //    DisplayRootViewFor<ShareTargetViewModel>();
        //}
    }
}
